package com.imooc.init;

import com.imooc.propterties.DataSourceProperty;
import com.imooc.util.EncryptUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
public class DecryptDataSourceInit implements DataSourceInit {
    @Override
    public void beforeCreate(DataSourceProperty dataSourceProperty) {
        String privateKey = dataSourceProperty.getPrivateKey();
        if (StringUtils.isNotEmpty(privateKey)) {
            dataSourceProperty.setUsername(decrypt(privateKey, dataSourceProperty.getUsername()));
            dataSourceProperty.setPassword(decrypt(privateKey, dataSourceProperty.getPassword()));
        }
    }

    @Override
    public void afterCreate(DataSourceProperty dataSourceProperty) {

    }

    private String decrypt(String privateKey, String cipherText) {
        if (StringUtils.isNotEmpty(cipherText)) {
            return EncryptUtil.rsaDecrypt(cipherText, privateKey, null);
        }
        return cipherText;
    }
}
